package com.example.a15787.weather_zyy_1235;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class WeatherParser {
    public static WeatherResponse parse(String jsonString) throws Exception {
        JSONObject json = new JSONObject(jsonString);
        WeatherResponse response = new WeatherResponse();
        JSONArray citiesArray = json.getJSONArray("cities");
        response.cities = parseCities(citiesArray);
        return response;
    }

    private static List<WeatherResponse.City> parseCities(JSONArray array) throws Exception {
        List<WeatherResponse.City> cities = new ArrayList<>();
        for (int i = 0; i < array.length(); i++) {
            JSONObject cityObj = array.getJSONObject(i);
            WeatherResponse.City city = new WeatherResponse.City();
            city.cityId = cityObj.getString("cityId");
            city.cityName = cityObj.getString("cityName");
            city.weatherForecast = parseForecasts(cityObj.getJSONArray("weatherForecast"));
            cities.add(city);
        }
        return cities;
    }

    private static List<WeatherResponse.Forecast> parseForecasts(JSONArray array) throws Exception {
        List<WeatherResponse.Forecast> forecasts = new ArrayList<>();
        for (int i = 0; i < array.length(); i++) {
            JSONObject forecastObj = array.getJSONObject(i);
            WeatherResponse.Forecast forecast = new WeatherResponse.Forecast();
            forecast.date = forecastObj.getString("date");
            forecast.weather = forecastObj.getString("weather");
            forecast.temperature = parseTemperature(forecastObj.getJSONObject("temperature"));
            forecast.humidity = forecastObj.optInt("humidity", 0); // 默认为0
            forecast.pm25 = forecastObj.optDouble("pm25", 0.0);
            forecast.wind = forecastObj.getString("wind");
            forecast.icon = forecastObj.getString("icon");
            forecasts.add(forecast);
        }
        return forecasts;
    }

    private static WeatherResponse.Temperature parseTemperature(JSONObject json) throws Exception {
        WeatherResponse.Temperature temperature = new WeatherResponse.Temperature();
        temperature.min = json.getInt("min");
        temperature.max = json.getInt("max");
        return temperature;
    }
}